package com.cqc.customdialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by ${cqc} on 2017/4/5.
 */

public class MainActivity2 extends AppCompatActivity {


    private static final String TAG = "MainActivity2";
    private Context context;
    private Button btn;

    private Calendar c = null;
    private Dialog dialog = null;
    private int today;
    private String pickDate;
    private String pickTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        context = this;
        btn = (Button) findViewById(R.id.btn3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCreateDialog(AppConstant.DATE_DIALOG);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        c = Calendar.getInstance();
        switch (id) {
            case AppConstant.DATE_DIALOG:
                dialog = new MyDatePickerDialog(this, new MyDatePickerDialog.OnDateSetListener() {
                    @SuppressWarnings("deprecation")
                    public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {
                        Log.d(TAG, "--year=" + year + ",month=" + month + ",dayOfMonth=" + dayOfMonth);
                        if (c.get(Calendar.YEAR) > year) {
                            Toast.makeText(context, "您选择的年份不对，请重新选择！", Toast.LENGTH_SHORT).show();
                            dialogDisplayOpear(false);// dialog显示控制-不关闭
                        } else if (c.get(Calendar.YEAR) == year) {
                            if (c.get(Calendar.MONTH) > month) {
                                Toast.makeText(context, "您选择的月份不对，请重新选择！", Toast.LENGTH_SHORT).show();
                                dialogDisplayOpear(false);// dialog显示控制-不关闭
                                // InitToast.initToast("您选择的月份不对，请重新选择！",context);
                            } else if (c.get(Calendar.MONTH) == month) {
                                if (c.get(Calendar.DAY_OF_MONTH) > dayOfMonth) {
                                    Toast.makeText(context, "您选择的日期不对，请重新选择！", Toast.LENGTH_SHORT).show();
                                    dialogDisplayOpear(false);// dialog显示控制-不关闭
                                    // InitToast.initToast("您选择的日不对，请重新选择！",context);
                                } else {
                                    if (c.get(Calendar.HOUR_OF_DAY) >= 22 && c.get(Calendar.DAY_OF_MONTH) == dayOfMonth) {
                                        Toast.makeText(context, "当日已无可预约时间，请选择其他日期", Toast.LENGTH_SHORT).show();
                                        dialogDisplayOpear(false);
                                    } else {
                                        pickDate = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(dayOfMonth);
                                        today = dayOfMonth;
                                        dialogDisplayOpear(true);// dialog显示控制-关闭
                                        onCreateDialog(AppConstant.TIME_DIALOG);
                                    }
                                }
                            } else {
                                pickDate = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(dayOfMonth);
                                today = dayOfMonth;
                                dialogDisplayOpear(true);// dialog显示控制-关闭
                                showDialog(AppConstant.TIME_DIALOG);
                            }
                        } else {
                            pickDate = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(dayOfMonth);
                            today = dayOfMonth;
                            dialogDisplayOpear(true);// dialog显示控制-关闭
                            showDialog(AppConstant.TIME_DIALOG);
                        }
                    }

                    private void dialogDisplayOpear(boolean isDisplay) {
                        try {
                            Field field = dialog.getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("mShowing");
                            field.setAccessible(true);
                            // 将mShowing变量设为false，表示对话框已关闭
                            field.set(dialog, isDisplay);
//                            dialog.dismiss();
                        } catch (Exception e) {
                        }
                    }
                }, c.get(Calendar.YEAR), // 传入年份
                        c.get(Calendar.MONTH), // 传入月份
                        c.get(Calendar.DAY_OF_MONTH) // 传入天数
                );
                dialog.show();
                break;
            case AppConstant.TIME_DIALOG:
                final String[] item = filtrateTime(today);
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setTitle("请选择预计到达时间");
                builder.setCancelable(false);

                final ChoiceOnClickListener choiceListener = new ChoiceOnClickListener();
                builder.setSingleChoiceItems(item, 0, choiceListener);

                builder.setNegativeButton("选择日期", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        onCreateDialog(AppConstant.DATE_DIALOG);
                    }

                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int which) {
                        int choiceWhich = choiceListener.getWhich();
                        String hobbyStr = item[choiceWhich];
                        pickTime = hobbyStr;
                        Log.d(TAG, "pickDate=" + pickDate + "pickTime=" + pickTime);
                        dialogInterface.dismiss();
                    }
                });
                builder.create().show();
                break;
        }
        return dialog;
    }

    private class ChoiceOnClickListener implements DialogInterface.OnClickListener {
        private int which = 0;

        public void onClick(DialogInterface dialogInterface, int which) {
            this.which = which;
        }

        public int getWhich() {
            return which;
        }
    }


    /**
     * 方法描述：过滤时间段 模块作者：Shawn-xiaolai 开发时间：2016年1月18日 下午5:26:14 更新记录：
     * 返回数据：String[]
     */
    private String[] filtrateTime(int today) {
        final String[] items = new String[]{"0:00-2:00", "2:00-4:00", "4:00-6:00", "6:00-8:00", "8:00-10:00",
                "10:00-12:00", "12:00-14:00", "14:00-16:00", "16:00-18:00", "18:00-20:00", "20:00-22:00", "22:00-24:00"};
        if (c.get(Calendar.DAY_OF_MONTH) == today) {
            ArrayList<String> list = new ArrayList<String>();
            for (int i = 0; i < items.length; i++) {
                if (c.get(Calendar.HOUR_OF_DAY) < Integer.parseInt(items[i].split("-")[0].replace(":00", ""))) {
                    list.add(items[i]);
                }
            }
            String[] newTime = (String[]) list.toArray(new String[list.size()]);
            return newTime;
        } else {
            return items;
        }
    }
}
